<template>
  <continer>
    <template slot="search">
      <QuickSearch :advForm="quickSearchForm" @QuickSearch="search"></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="search">查询</el-button>
      <el-button size="mini" @click="addTimeCondition" v-functions="['docking_setting_event_send_insert']">新增</el-button>
    </template>
    <template slot="content">
      <configTable
              :headers="tableHeaders"
              :data="tableData"
              :pagingData="pagingData"
              @pageChange="pageChange"
              @pageSizeChange="pageSizeChange"
              @checkHeadersChange="checkHeadersChange">
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
                    :show-overflow-tooltip="true"
                    :resizable="false"
                    :prop="item.prop"
                    :label="item.label"
                    :key="index"
                    :sortable="item.sortable"
                    v-if="item.show && item.prop !== 'oprate' && item.prop !== 'eventType'">
            </u-table-column>
            <u-table-column
                    :resizable="false"
                    :prop="item.prop"
                    :label="item.label"
                    :key="index"
                    :sortable="item.sortable"
                    v-if="item.show && item.prop === 'eventType'">
                <template slot-scope="scope">
                  <span>{{scope.row.eventType | getEventType}}</span>
                </template>
            </u-table-column>
            <u-table-column
                    :label="item.label"
                    :width="80"
                    fixed="right"
                    :key="index"
                    v-if="item.prop === 'oprate' && item.show">
              <template slot-scope="scope">
                <span @click="editTimeCondition(scope.row)" class="oprate-span" v-functions="['docking_setting_event_send_edit']">编辑</span>
                <span @click="deleteTimeCondition(scope.row)" class="delete-span oprate-span" v-functions="['docking_setting_event_send_delete']">删除</span>
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
      <AddOrEditEvent :type="type" ref="eventRef" @refresh="fetchData"></AddOrEditEvent>
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import configTable from '@/components/configCommon/table.vue'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import AddOrEditEvent from './AddOrEditEvent.vue'
import { SystemConfigModule } from '@/store/modules/config/systemConfig'
interface DrawerObj {
    type: string
    form: object
}

interface PageData {
    total: number
    limit: number
    page: number
}
@Component({
  name: 'TimeConditions',
  components: { continer, configTable, AddOrEditEvent, QuickSearch },
  filters: {
    getEventType (type) {
      let label
      switch (type) {
        case 'dialoutRing':
          label = '外呼振铃事件'
          break;
        case 'dialoutHangup':
          label = '外呼挂机事件'
          break;
        case 'incomingRing':
          label = '来电振铃事件'
          break;
        case 'incomingHangup':
          label = '来电挂机事件'
          break;
        case 'cdr':
          label = '通话记录推送事件'
          break;
        case 'link':
          label = '客户接通事件'
          break;
        case 'callStatus':
          label = '座席状态变化事件'
          break;
        case 'mediaFailreason':
          label = '媒体识别挂机原因事件'
          break;
        case 'loginStatus':
          label = '电话条登录状态事件'
          break;
        case 'QueueStart':
          label = '排队开始事件'
          break;
        case 'SALE_SPARE_CHANGE':
          label = '备件变更'
          break;
        case 'SALE_SERVICE_PROJECT_ITEM_CHANGE':
          label = '服务项目品类变更'
          break;
        case 'SALE_SPARE_RK':
          label = '备件入库'
          break;
        case 'SALE_SPARE_CK':
          label = '备件出库'
          break;
        case 'QueueEnd':
          label = '排队结束事件'
      }
      return label
    }
  }
})
export default class extends Vue {
  [x: string]: any
  @Ref() private readonly eventRef !: AddOrEditEvent
  private type: string = 'add' // 当前是添加还是编辑，用抽屉里的数据操作区分
  private pagingData: PageData = { total: 0, limit: 10, page: 1 } // 翻页相关的数据控制
  private tableHeaders: object[] = [ // 基本表头配置信息
    { label: '事件类型', prop: 'eventType' },
    { label: '推送地址', prop: 'pushUrl' },
    { label: '说明', prop: 'description' },
    { label: '最后操作人', prop: 'updateUserName' },
    { label: '最后更新时间', prop: 'updateTime' },
    { label: '操作', prop: 'oprate' }
  ]

  private typeArr: object[] = [ // 搜索事件类型下拉
    { name: '外呼振铃事件', _id: 'dialoutRing' },
    { name: '外呼挂机事件', _id: 'dialoutHangup' },
    { name: '来电振铃事件', _id: 'incomingRing' },
    { name: '来电挂机事件', _id: 'incomingHangup' },
    { name: '通话记录推送事件', _id: 'cdr' },
    { name: '客户接通事件', _id: 'link' },
    { name: '座席状态变化事件', _id: 'callStatus' },
    { name: '媒体识别挂机原因事件', _id: 'mediaFailreason' },
    { name: '电话条登录状态事件', _id: 'loginStatus' },
    { name: '排队开始事件', _id: 'QueueStart' },
    { name: '排队结束事件', _id: 'QueueEnd' },
    { name: '备件变更', _id: 'SALE_SPARE_CHANGE' },
    { name: '备件入库', _id: 'SALE_SPARE_RK' },
    { name: '备件出库', _id: 'SALE_SPARE_CK' },
    { name: '服务项目品类变更', _id: 'SALE_SERVICE_PROJECT_ITEM_CHANGE' }
  ]

  private quickSearchForm = { // 快捷检索数据(事件类型)
    form: {
      eventType: []
    },
    advSearchOptions: [ // 快捷检索的数据(语音文件名称)
      { label: '事件类型', inputType: 'select', clearable: true, multiple: true, selectData: this.typeArr, name: 'eventType' }
    ]
  }

  private checkHeaders: [] = [] // 当前展示的表头

  private tableData: object[] = [] // table展示的数据

  private addTimeCondition () { // 添加事件推送
    this.type = 'add'
    this.eventRef.openOrCloseDrawer(null)
  }

  private editTimeCondition (row: any) { // 编辑事件推送
    this.type = 'edit'
    this.eventRef.openOrCloseDrawer(row)
  }

  private search () { // 点击查询
    this.pagingData.page = 1
    this.fetchData(null)
  }

  private pageChange (page) { // 翻页
    this.pagingData.page = page
    this.fetchData(null)
  }

  private pageSizeChange (size) { // 每页多少条数据
    this.pagingData.limit = size
    this.pagingData.page = 1
    this.fetchData(null)
  }

  private deleteTimeCondition (row: any) { // 删除时间条件
    this.$confirm('确定删除该事件类型吗', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const data = { url: '/base/action/general/docking/delete', method: 'POST', data: { _id: row._id } }
      SystemConfigModule.SystemCommonAction(data).then((res: any) => {
        if (res && res.success) {
          this.$message({ message: '删除成功', type: 'success' })
          this.fetchData(null)
        }
      })
    }).catch(e => {
      console.log(e)
    })
  }

  private checkHeadersChange (checkList) { // 设置当前展示的表头信息
    this.$set(this, 'checkHeaders', checkList)
  }

  private fetchData (addSuccess) { // 查列表
    if (addSuccess) { // 新增回到第一页
      this.pagingData.page = 1
    }
    const actionData = Object.assign({ limit: this.pagingData.limit, page: this.pagingData.page }, this.quickSearchForm.form)
    const data = { url: '/base/action/general/docking/list', method: 'POST', data: actionData }
    SystemConfigModule.SystemCommonAction(data).then((res: any) => {
      if (res && res.success && res.data) {
        const list = res.data.list || []
        if (list.length === 0) {
          const page = Math.ceil(res.data.count / this.pagingData.limit)
          if (!res.data.count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.pagingData.page = 1
          } else { // 删除到最后一个回到上一页
            this.pagingData.page = page
            this.fetchData(null)
            return false
          }
        }
        list.forEach((item: any) => {
          const agentObj = this.$store.state.common.publicCache.userListObj[item.updateUser]
          item.updateUserName = agentObj ? agentObj.name : '--'
        })
        this.tableData = list
        this.pagingData.total = res.data.count || 0
      }
    })
  }

  private beforeMount () {
    this.fetchData(null)
  }
}
</script>

<style lang="stylus" scoped>
  .oprate-span,.radio-span
    cursor pointer
    color $c-main
  .delete-span
    color $c-danger
    padding-left 10px
  .radio-span
    width 24px
    height 24px
    display inline-block
    background #fff
    margin 2px 0px 2px 0
    box-shadow 0px 1px 3px 0px rgba(216, 222, 230, 0.9)
    border-radius 50%
    font-size 12px
    color $c-main
    text-align center
    vertical-align middle
    &:last-child
     margin-right 0
     margin-left 10px
</style>
